/**
 * Created by yanglizhe on 2016/1/11.
 */

(function($){

    "use strict"

    /**
     * 选择器
     * @param config
     * @constructor
     */
    function SimpleSelector(config){
        this.__construct(config);
    }

    SimpleSelector.prototype = {
        __construct:function(config){
            this.container= config.container;
            this.maxLength = config.maxLength || 3;
            this.type = config.type || "number";
            this.initHtml(config.options);
            this.bindEvent();
        },
        initHtml:function(options){//初始化结构
            var stringBuffer = [];
            for(var i=0; i< options.length; i++){
                var option = options[i];
                stringBuffer.push('<li data-value="'+ option +'" class="option">' + option +'</li>');
            }
            stringBuffer.push('<li class="option custom-option"><input class="user-input" data-type="'+ this.type+ '" placeholder="自定义" type="text" maxlength="'+this.maxLength+'" /></li>');

            var html = '<ul class="simple-select">'+stringBuffer.join("\n")+'</ul>';
            this.container.html(html);
        },
        bindEvent:function(){
            this.find(".option:first").addClass("selected");
            this.find(".option").bind("click", function(){
                $(this).siblings().removeClass("selected");
                $(this).addClass("selected");
            });

            this.find("[data-type='number']").bind("input", function(){
                var number = $.trim($(this).val());
                number = number.replace(/[^\d]/g, "").replace(/^0+/g, '');
                if($(this).attr("max")){
                    var max = parseInt($(this).attr("max"));
                    while(number > max){
                        number = Math.floor( number / 10 );
                    }
                }

                if(number != $(this).val() || number==''){
                    $(this).val(number);
                }

            });

        },
        find:function(selector){
            return $(selector, this.container);
        }

    };

    $.fn.simpleSelector = function(config){
        return this.each(function(){
            var _config = $.extend(true, {
                container : $(this)
            }, config);
            console.log(_config);
            new SimpleSelector(_config);
        });
    }



})(jQuery);
